<template>
  <el-dialog title="编辑风险对象" :visible.sync="visible" width="50%" :before-close="handleClose">
    <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-position="right">
      <el-form-item label="风险分析对象" :label-width="formLabelWidth" prop="oName">
        <el-input v-model="ruleForm.oName" placeholder="请输入风险分析对象"  style="width:90%;" />
      </el-form-item>
      
      <el-form-item label="分类" :label-width="formLabelWidth" prop="oType">
        <el-select v-model="ruleForm.oType" placeholder="请选择"  style="width:90%;">
          <el-option v-for="item in OTYPESelect" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="编码" :label-width="formLabelWidth" prop="hazardCode">
        <el-input v-model="ruleForm.hazardCode" placeholder="请输入编码"  style="width:90%;" disabled />
      </el-form-item>

      <el-form-item label="是否重大危险源" :label-width="formLabelWidth" prop="oIfRisk">
        <el-radio-group v-model="ruleForm.oIfRisk" @change="handleOIFRISKChange">
          <el-radio label="0">是</el-radio>
          <el-radio label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否管控" :label-width="formLabelWidth" prop="whether">
        <el-radio-group v-model="ruleForm.whether">
          <el-radio label="0">是</el-radio>
          <el-radio label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="责任部门" :label-width="formLabelWidth" prop="hazardDep">
        <el-input 
          v-model="ruleForm.hazardDep" 
          placeholder="请选择责任部门" 
          readonly 
           style="width:90%;"
          @click.native="chooseUnit('hazardDep')"
        />
      </el-form-item>

      <el-form-item label="操作责任人" :label-width="formLabelWidth" prop="czHazard">
        <el-input 
          v-model="ruleForm.czHazard" 
          placeholder="请选择操作责任人" 
          readonly
           style="width:90%;" 
          @click.native="choosePersonnel('czHazard', {multiple: false})"
        />
      </el-form-item>

      <template v-if="showExtraFields">
        <el-form-item label="技术责任人" :label-width="formLabelWidth" prop="jsHazard">
          <el-input 
            v-model="ruleForm.jsHazard" 
            placeholder="请选择技术责任人" 
            readonly
             style="width:90%;" 
            @click.native="choosePersonnel('jsHazard', {multiple: false})"
          />
        </el-form-item>

        <el-form-item label="主要责任人" :label-width="formLabelWidth" prop="zyHazard">
          <el-input 
            v-model="ruleForm.zyHazard" 
            placeholder="请选择主要责任人" 
            readonly
             style="width:90%;" 
            @click.native="choosePersonnel('zyHazard', {multiple: false})"
          />
        </el-form-item>
      </template>
    </el-form>
    
    <el-dialog
      title="选择申请单位信息"
      top="12vh"
      :modal="false"
      :visible.sync="dialogFormVisibleUnit"
      width="30%"
      :before-close="handleDialogClose"
      append-to-body
    >
      <companyTree 
        :key="timerUnit" 
        @setCheckedList="getCheckedUintList" 
        :echoCheckedLabel="echoCheckedUnitLabel"
      ></companyTree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleUnit = false">取 消</el-button>
        <el-button type="primary" @click="confirmUnit">确 定</el-button>
      </span>
    </el-dialog>

    <el-drawer 
      title="人员选择" 
      :visible.sync="dialogFormVisiblePersonnel" 
      :modal="false" 
      size="50%" 
      :with-header="false"
    >
      <personnelSelection
        :multiple="multiple"
        @setCheckedList="getCheckedPersonnelList"
        :key="timerPersonnel"
        :echoCheckedLabel="echoCheckedLabel"
      >
      </personnelSelection>
    </el-drawer>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')" :disabled="!buttonEnabled">
        {{ buttonEnabled ? '确 定' : '修改中...' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { useriskObjectApi } from '@/api/riskObjectApi';
import companyTree from "@/components/companyTree/index.vue";
import personnelSelection from '@/components/personnelSelection';

export default {
  name: 'EditDevice',
  components: {
    companyTree,
    personnelSelection
  },
  data() {
    return {
      visible: false,
      formLabelWidth: '150px',
      showExtraFields: false,
      buttonEnabled: true,
      ruleForm: {
        oName: '',
        oType: '',
        hazardCode: '',
        oIfRisk: '1',
        hazardDep: '',
        hazardDepId: '',
        whether: '0',
        zyHazard: '',
        zyHazardId: '',
        jsHazard: '',
        jsHazardId: '',
        czHazard: '',
        czHazardId: '',
      },
      OTYPESelect: [
        { value: '0', label: '生产装置' },
        { value: '1', label: '罐区' }
      ],
      rules: {
        oName: [{ required: true, message: '请输入风险分析对象', trigger: 'blur' }],
        oType: [{ required: true, message: '请选择分类', trigger: 'change' }],
        hazardCode: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        oIfRisk: [{ required: true, message: '请选择是否重大危险源', trigger: 'change' }],
        whether: [{ required: true, message: '请选择是否管控', trigger: 'change' }],
        hazardDep: [{ required: true, message: '请输入责任部门', trigger: 'change' }],
        czHazard: [{ required: true, message: '请输入操作责任人', trigger: 'change' }],
        jsHazard: [{ 
          required: true, 
          message: '请输入技术责任人', 
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ruleForm.oIfRisk === '0' && !value) {
              callback(new Error('请输入技术责任人'))
            } else {
              callback()
            }
          }
        }],
        zyHazard: [{ 
          required: true, 
          message: '请输入主要责任人', 
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ruleForm.oIfRisk === '0' && !value) {
              callback(new Error('请输入主要责任人'))
            } else {
              callback()
            }
          }
        }]
      },
      dialogFormVisibleUnit: false,
      echoCheckedUnitLabel: [],
      timerUnit: null,
      unitType: '',
      unitIdStr: '',
      unitNameStr: '',
      formFields: {
        hazardDep: {
          id: 'hazardDepId'
        }
      },
      dialogFormVisiblePersonnel: false,
      multiple: false,
      timerPersonnel: null,
      PersonnelType: '',
      PersonnelIdStr: '',
      PersonnelNameStr: '',
      echoCheckedLabel: [],
      list: {}
    }
  },
  methods: {
    handleOIFRISKChange(value) {
      this.showExtraFields = value === '0'
    },
    show(row) {
      this.visible = true
      this.$nextTick(() => {
        this.ruleForm = { ...row }
        this.showExtraFields = this.ruleForm.oIfRisk === '0'
      })
    },
    handleClose() {
      this.buttonEnabled = true
      this.$refs.ruleForm?.resetFields()
      this.ruleForm = {
        oName: '',
        oType: '',
        hazardCode: '',
        oIfRisk: '1',
        hazardDep: '',
        hazardDepId: '',
        whether: '0',
        zyHazard: '',
        zyHazardId: '',
        jsHazard: '',
        jsHazardId: '',
        czHazard: '',
        czHazardId: '',
        deleted: '0'
      }
      this.showExtraFields = false
      this.visible = false
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.buttonEnabled = false
          useriskObjectApi().updateObject(this.ruleForm).then(res => {
            if (res.code * 1 === 100) {
              this.$message.success('修改成功')
              this.$emit('success')
              this.handleClose()
              setTimeout(() => {
                this.buttonEnabled = true
              }, 500)
            } else {
              this.$message.error(res.message || '修改失败')
              this.buttonEnabled = true
            }
          }).catch(err => {
            console.error('修改失败:', err)
            this.$message.error('修改失败，请稍后重试')
            this.buttonEnabled = true
          })
        } else {
          return false
        }
      })
    },
    chooseUnit(value) {
      this.timerUnit = new Date().getTime()
      this.dialogFormVisibleUnit = true
      this.unitType = value
      this.echoCheckedUnitLabel = this.ruleForm[value] ? this.ruleForm[value].split(",") : [];
    },
    confirmUnit() {
      const fieldConfig = this.formFields[this.unitType]
      const nameKey = this.unitType;
      const idKey = fieldConfig.id;
      
      this.$set(this.ruleForm, nameKey, this.unitNameStr);
      this.$set(this.ruleForm, idKey, this.unitIdStr);
      this.dialogFormVisibleUnit = false;
    },
    getCheckedUintList(list) {
      this.unitIdStr = list.map((i) => i.id).join(',')
      this.unitNameStr = list.map((i) => i.label).join(',')
    },
    handleDialogClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    choosePersonnel(type, field) {
      this.PersonnelType = type;
      this.multiple = field.multiple;
      this.timerPersonnel = new Date().getTime();
      this.dialogFormVisiblePersonnel = true;
      this.echoCheckedLabel = this.ruleForm[type] ? this.ruleForm[type].split(',') : [];
    },
    getCheckedPersonnelList(list) {
      let arr = list.map((i) => {
        return { name: i.name, id: i.id, type: i.type };
      });
      this.list[this.PersonnelType] = arr;
      this.PersonnelIdStr = list.map((i) => i.id).join(',');
      this.PersonnelNameStr = list.map((i) => i.name).join(',');
      this.personConfirm();
    },
    personConfirm() {
      const nameKey = this.PersonnelType;
      const idKey = `${nameKey}Id`;
      
      this.$set(this.ruleForm, nameKey, this.PersonnelNameStr);
      this.$set(this.ruleForm, idKey, this.PersonnelIdStr);
      this.dialogFormVisiblePersonnel = false;
    }
  }
}
</script> 